from aiogram import F, Router, types
from aiogram.filters import Command
from aiogram.fsm.context import FSMContext
from loguru import logger

from database import models
from tg_bot.filters.user_filter import IsAdmin
from tg_bot.keyboards import inline, callback_factory as cf
from tg_bot.states.admin import AdminCmd


router = Router()
router.message.filter(IsAdmin())
router.callback_query.filter(IsAdmin())


@router.message(Command('open_shift'))
async def open_shift_cmd(message: types.Message,
                         state: FSMContext):
    key = await inline.team_choice()
    text = 'Выберите, кто открывает смену: '
    await message.answer(text, reply_markup=key)
    await state.set_state(AdminCmd.work_shift)
    await state.update_data({'shift_action': 'open'})


@router.message(Command('close_shift'))
async def close_shift_cmd(message: types.Message,
                          state: FSMContext):
    text = 'Выберите, кто закрывает смену: '
    key = await inline.team_choice()
    await message.answer(text, reply_markup=key)
    await state.set_state(AdminCmd.work_shift)
    await state.update_data({'shift_action': 'close'})


@router.callback_query(
    cf.TeamCall.filter(),
    AdminCmd.work_shift
)
async def team_choice_call(call: types.CallbackQuery,
                           state: FSMContext,
                           callback_data: cf.TeamCall):
    data = await state.get_data()
    shift_action: str = data.get('shift_action')
    team: models.Team = models.Team.objects.get(pk=callback_data.pk)
    if shift_action == 'open':
        opened, shift = models.WorkShift.open_shift(team)
        if opened:
            text = 'Вы успешно открыли смену!'
        else:
            text = 'У вас уже имеется открытая смена! Ее нужно сначала закрыть!'
    else:
        if models.WorkShift.close_shift(team):
            text = 'Вы успешно закрыли смену!'
        else:
            text = 'У вас нет открытой смены! Пропишите /open_shift'
    try:
        await call.message.edit_text(text)
    except Exception as e:
        logger.warning(e)
        await call.message.answer(text)
    await state.clear()
